package org.budo.mongo.jdbc.driver.statement.impl;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Map;

import org.bson.Document;
import org.budo.mongo.jdbc.driver.BudoMongoJdbcPreparedStatement;
import org.budo.mongo.jdbc.driver.BudoMongoJdbcResultSetMetaData;
import org.budo.mongo.jdbc.driver.resultset.RowsResultSet;
import org.budo.mongo.jdbc.driver.statement.AbstractMongoStatement;
import org.budo.support.slf4j.Slf4j;
import org.slf4j.Logger;

import com.mongodb.client.MongoCollection;

/**
 * @author li
 */
public class MongoCountStatement extends AbstractMongoStatement {
    private static final Logger log = Slf4j.getLogger();

    public void execute(PreparedStatement preparedStatement) throws SQLException{
        BudoMongoJdbcPreparedStatement mongoPreparedStatement = (BudoMongoJdbcPreparedStatement) preparedStatement;
        MongoCollection<Document> mongoCollection = this.getMongoCollection(mongoPreparedStatement);
        Map<String, Object> statementDocument = this.getStatementDocumentWithParameterValues(mongoPreparedStatement.getParameterMap());

        log.debug("execute(), statementDocument={}, sql={}, parameterMap={}", statementDocument, this.sql(), mongoPreparedStatement.getParameterMap());

        Map<String, Object> whereDocument = (Map<String, Object>) statementDocument.get(WHERE);

        long count;
        if (null == whereDocument) {
            count = mongoCollection.count();
        } else {
            count = mongoCollection.count(new Document(whereDocument));
        }

        RowsResultSet rowsResultSet = new RowsResultSet();
        BudoMongoJdbcResultSetMetaData resultSetMetaData = this.getResultSetMetaData();
        rowsResultSet.setMetaData(resultSetMetaData);
        Object[][] dataRows = new Object[][] { { count } };
        rowsResultSet.setResultSetData(dataRows);

        mongoPreparedStatement.resultSet(rowsResultSet);
    }
}